<?php

// @formatter:off
/**
 * @file update.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-06-03 03:40:32 +0000 (Tue, 03 Jun 2014) $
 *
 * $Id: update.php 112 2014-06-03 03:40:32Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/services/users/update.php $
 */
// @formatter:on

require_once __DIR__."/tools.php";

class WCServiceUsersUpdate extends WCService {
	//
	// Class methods.
	public function __construct() {
		parent::__construct();

		$this->_readOnlyConflict = true;

		$this->_requiredParams["params"][] = "user";
		$this->_requiredParams["params"][] = "basics";
		$this->_requiredParams["params"][] = "data";

		$this->_requiredPermissions["any"][] = WC_PERM_USER_EDIT;
		$this->_requiredPermissions["any"][] = WC_PERM_USER_SELF_EDIT;
	}
	//
	// Public methods.
	public function check() {
		if(parent::check()) {
			global $wcProfile;
			global $wcUser;

			if(!$wcUser || !$wcUser->ok()) {
				$this->setError(WC_HTTPERROR_BAD_REQUEST, "No valid user specified");
			}
			if($this->user && $wcUser && $wcUser->ok() && $this->_user != $wcUser->id()) {
				$this->setError(WC_HTTPERROR_BAD_REQUEST, "You are not allowed to edit other user's information");
			}
			if($this->user && $wcUser && $wcUser->ok() && !$wcProfile->allowedTo(WC_PERM_USER_EDIT)) {
				$this->setError(WC_HTTPERROR_BAD_REQUEST, "You don't have privileges to edit other user's information");
			}
		}

		return $this->ok();
	}
	//
	// Protected methods.
	protected function runPOST() {
		global $wcUsersHolder;

		$user = $wcUsersHolder->item($this->user);
		if($user && $user->ok()) {
			global $wcUserXData;
			//
			// Updating user extra data.
			$data = $user->data();
			foreach($wcUserXData["_names"] as $name) {
				if(isset($this->data[$name]) && $this->data[$name] != $data->getExtra($name)) {
					$data->setExtra($name, $this->data[$name]);
					$this->_count++;
				}
			}
			//
			// Updating full-name.
			if(isset($this->basics["FULLNAME"]) && $this->basics["FULLNAME"] != $data->fullname) {
				$data->fullname = $this->basics["FULLNAME"];
				$this->_count++;
			}
			if(isset($this->basics["EMAIL"]) && $this->basics["EMAIL"] != $data->email) {
				$euser = $wcUsersHolder->userByEmail($this->basics["EMAIL"]);
				if($euser) {
					$this->setError(WC_HTTPERROR_BAD_REQUEST, "E-mail '{$this->basics["EMAIL"]}' is been used by another user");
				} else {
					$data->email = $this->basics["EMAIL"];
					$this->_count++;
				}
			}
		} else {
			$this->setError(WC_HTTPERROR_BAD_REQUEST, "Not valid user");
		}
	}
}
